import { createElement } from "../../utils";

interface HiMenuItem {
  key?: string | number;
  icon?: string;
  label: string;
}

export class HiMenu {
  element = createElement("div", { className: "hi-menu" });
  private _open = false;

  get open() {
    return this._open;
  }

  set open(value) {
    this._open = value;
    if (value) {
      this.element.classList.add("open");
    } else {
      this.element.classList.remove("open");
    }
  }

  private _items: HiMenuItem[] = [];

  private _onclick = (item: HiMenuItem, index: number) => { }

  constructor(items: HiMenuItem[] = []) {
    this._items = items;
    this.render();
  }

  private render() {
    this.element.innerHTML = "";
    this._items.forEach((item, index) => {
      const menuItem = createElement("div", { className: "hi-menu-item" });
      const icon = createElement("i", { content: item.icon });
      const label = createElement("span", { content: item.label });
      menuItem.append(icon, label);
      this.element.append(menuItem);
      menuItem.onclick = () => this._onclick(item, index)
    })
    if (!this.element.parentElement) document.body.append(this.element);
  }

  setPosition(x: number, y: number, items?: HiMenuItem[]) {
    if (items) {
      this._items = items;
      this.render();
    }
    this.element.style.left = `${x}px`;
    this.element.style.top = `${y}px`;
    this.open = true;
    return this;
  }


  onClick(fn: (item: HiMenuItem, index: number) => void) {
    this._onclick = fn
    return this;
  }
}